
package com.joysuch.wwyt.config;

import java.util.concurrent.atomic.AtomicInteger;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.redisson.config.TransportMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * redis通用配置类
 */
@SuppressWarnings("rawtypes")
@Configuration
@PropertySource(value = "classpath:redis.properties", encoding = "UTF-8")
@Slf4j
public class RedissonConfig {

    @Value("${redis.pool.maxActive}")
    private Integer maxTotal;

    @Value("${redis.pool.maxIdle}")
    private Integer maxIdle;

    @Value("${redis.pool.maxWait}")
    private Integer maxWaitMillis;

    @Value("${redis.pool.testOnBorrow}")
    private Boolean testOnBorrow;

    @Value("${redis.hostname}")
    private String hostName;

    @Value("${redis.port}")
    private Integer port;

    @Value("${redis.password}")
    private String password;

    private AtomicInteger redissonExecutorThread = new AtomicInteger();
    @Autowired
    @Qualifier("overWriteConnectionFactory")
    private RedisConnectionFactory redisDb1ConnectionFactory;

    @Bean(value = "redissonClient")
    public RedissonClient redissonClient() {
        Config config = new Config();
        String redisAddr = "redis://" + hostName + ":" + port;
        SingleServerConfig singleServerConfig = config.useSingleServer();
        if (password != null && password.trim().length() > 0) {
            singleServerConfig.setPassword(password);
        }
        singleServerConfig.setAddress(redisAddr);
        singleServerConfig.setConnectionPoolSize(20);
        singleServerConfig.setConnectionMinimumIdleSize(20);
        config.setCodec(new StringCodec());
        config.setTransportMode(TransportMode.NIO);
        config.setNettyThreads(1);
        return Redisson.create(config);
    }

     @Bean
     RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        return container;
    }
}
